package com.qst.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.order.domain.Product;
import com.qst.order.domain.ReplenishRecord;
import com.qst.order.mapper.ProductMapper;
import com.qst.order.mapper.ReplenishRecordMapper;
import com.qst.order.service.ReplenishRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class ReplenishRecordServiceImpl extends ServiceImpl<ReplenishRecordMapper, ReplenishRecord> implements ReplenishRecordService {

    private final ProductMapper productMapper;

    // 构造注入
    private final ReplenishRecordMapper replenishRecordMapper;

    /**
     * 批量创建补货记录（配合批量补货业务）
     * @param productIds 商品ID列表
     * @param replenishQuantity 补货数量（统一）
     * @param reason 补货原因
     * @param method 补货方式
     * @param remark 备注
     * @param operateUserId 操作人员ID
     * @param operateUserName 操作人员姓名
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchCreateRecord(List<Integer> productIds,
                                  Integer replenishQuantity, String reason,
                                  String method, String remark,
                                  Integer operateUserId, String operateUserName) {
        // 1. 生成唯一批量批次号
        // 时间戳（毫秒）+ UUID全量，几乎不可能重复
        String batchId = "REPLENISH_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
        // 2. 批量查询商品当前库存（用于记录 pre_stock）
        List<Product> products = productMapper.selectByIds(productIds);
        
        // 3. 构造补货记录列表
        List<ReplenishRecord> records = new ArrayList<>();
        for (Product product : products) {
            ReplenishRecord record = new ReplenishRecord();
            record.setProductId(product.getProductId());
            record.setBatchId(batchId);
            record.setPreStock(product.getStock()); // 补货前库存（当前商品库存）
            record.setReplenishQuantity(replenishQuantity);
            record.setAfterStock(product.getStock() + replenishQuantity); // 补货后库存
            record.setReplenishReason(reason);
            record.setReplenishMethod(method);
            record.setRemark(remark);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setOperateUserId(operateUserId);
            record.setOperateUserName(operateUserName);
            record.setReplenishStatus(1); // 默认为“完成”状态
            records.add(record);
        }
        // 4. 批量插入补货记录（MyBatis-Plus 批量插入，效率高）
      replenishRecordMapper.insert(records);

        // 5. 更新商品库存
       productMapper.batchReplenish(productIds, replenishQuantity,LocalDateTime.now());
    }

    /**
     * 单个商品创建补货记录（配合单个补货业务）
     * @param productId 商品ID
     * @param replenishQuantity 补货数量
     * @param reason 补货原因
     * @param remark 备注
     * @param operateUserId 操作人员ID
     * @param operateUserName 操作人员姓名
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createSingleRecord(Integer productId,
                                   Integer replenishQuantity, String reason,
                                   String remark, Integer operateUserId, String operateUserName) {
        // 1. 查询商品当前库存
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在，无法创建补货记录");
        }
        ReplenishRecord record = new ReplenishRecord();
        record.setPreStock(product.getStock());// 补货前库存（当前商品库存）

        // 2. 构造单个补货记录（batch_id 为 null，标识单个补货）

        record.setProductId(productId);
        record.setBatchId(null); // 单个补货无批次号

        record.setReplenishQuantity(replenishQuantity);
        record.setAfterStock(product.getStock() + replenishQuantity);
        record.setReplenishReason(reason);
        record.setReplenishMethod(null); // 单个补货若未传方式，可设为null
        record.setRemark(remark);
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        record.setOperateUserId(operateUserId);
        record.setOperateUserName(operateUserName);
        record.setReplenishStatus(1);
        // 3. 插入记录
       replenishRecordMapper.insert(record);

        //// 更新商品库存
        UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
        productUpdateWrapper.eq("product_id", productId);
        productUpdateWrapper.set("stock", product.getStock() + replenishQuantity);
        productUpdateWrapper.set("update_time", LocalDateTime.now());
        productMapper.update(productUpdateWrapper);
    }
}